//
//  SINAStuActivityAddImpressionViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2018/1/23.
//  Copyright © 2018年  androidlongs. All rights reserved.
//

#import "SINAStuActivityAddImpressionViewController.h"
#import "SINAUiviewClickLiserner.h"
#import "SINAPhotoPopView.h"

@interface SINAStuActivityAddImpressionViewController ()<UITextViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>


//附件列表
@property(nonatomic,strong) NSMutableArray *otherImageArray;
//标题
@property (weak, nonatomic) IBOutlet UILabel *titleUiLabel;
//分割线
@property (weak, nonatomic) IBOutlet UIView *diviView;
@property (weak, nonatomic) IBOutlet UITextView *inputDesTextView;
@property (weak, nonatomic) IBOutlet UIView *addImageView;
@property (weak, nonatomic) IBOutlet UIImageView *addImageView2;
//字数限制显示
@property (weak, nonatomic) IBOutlet UILabel *textNumberLabel;

@property (weak, nonatomic) IBOutlet UIView *mainContentView;
@property (weak, nonatomic) IBOutlet UIView *mainSelectImageContentView;


@property(nonatomic) NSInteger selectImageNumber;

@property(nonatomic) CGRect            preframe;
//选择图片的宽度
@property(nonatomic) NSInteger imageWidth;

@property(nonatomic) BOOL isUpLoading;
@end

@implementation SINAStuActivityAddImpressionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"随笔";
    UIView *rightView =[[UIView alloc]initWithFrame:CGRectMake(0,0,40,50)];
    UIButton *rightButton =[[UIButton alloc]initWithFrame:CGRectMake(0,0,40,45)];
    [rightButton addTarget:self action:@selector(uploadDataFunction) forControlEvents:UIControlEventTouchUpInside];
    [rightView addSubview:rightButton];
    [rightButton setTitle:@"确定" forState:UIControlStateNormal];
    UIBarButtonItem *rightButtonView = [[UIBarButtonItem alloc]initWithCustomView:rightView ];
    self.navigationItem.rightBarButtonItem=rightButtonView;
    self.isUpLoading = NO;
    
    
    self.otherImageArray=[[NSMutableArray alloc]init];
    
    self.imageWidth=(mainW-30 -30)/3;
    
    self.titleUiLabel.frame=CGRectMake(0, 0, mainW, 46);
    self.diviView.frame=CGRectMake(15, CGRectGetMaxY(self.titleUiLabel.frame), mainW-30, 1);
    self.inputDesTextView.frame=CGRectMake(15, CGRectGetMaxY(self.diviView.frame)+10, mainW-30, 110);
    self.textNumberLabel.frame=CGRectMake(15, CGRectGetMaxY(self.inputDesTextView.frame)+4, mainW-30, 21);
    
    self.mainSelectImageContentView.frame=CGRectMake(15, CGRectGetMaxY(self.textNumberLabel.frame)+15, mainW-30, self.imageWidth+15);
    self.addImageView.frame=CGRectMake(0, 15,self.imageWidth,self.imageWidth);
    self.addImageView2.frame=CGRectMake(0, 0,self.imageWidth,self.imageWidth);
    self.preframe=CGRectMake(-15, 15,0,0);
    
    self.mainContentView.frame=CGRectMake(0, 0, mainW, CGRectGetMaxY(self.mainSelectImageContentView.frame)+15);
    
    self.inputDesTextView.delegate=self;
    
    
    self.inputDesTextView.backgroundColor = [UIColor whiteColor];
    self.mainSelectImageContentView.backgroundColor = [UIColor whiteColor];
    
    
    __weak typeof(self) weakSelf = self;
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.view andWithBlick:^(UIView *view) {
        [weakSelf.view endEditing:YES];
    }];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.addImageView andWithBlick:^(UIView *view) {
        [weakSelf.view endEditing:YES];
        SINAPhotoPopView *popView =[[SINAPhotoPopView alloc]init];
        popView.isShowSaveImage=YES;
        [popView show];
        
        popView.creatPhopeBlock = ^{
            [weakSelf openPhote:1];
            
        };
        popView.selectPhopeBlock = ^{
            [weakSelf openPhote:2];
        };
        
    }];
    
}
-(void)openPhote :(NSInteger) flag{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    //可编辑
    picker.allowsEditing = NO;
    //判断是否可以打开照相机
    if (flag==1) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            //摄像头
            //UIImagePickerControllerSourceTypeSavedPhotosAlbum:相机胶卷
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        } else { //否则打开照片库
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
    }else{
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    [self presentViewController:picker animated:YES completion:nil];
}
#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if(textView.text.length < 1){
        textView.text = @"此时想写些什么呢...";
        textView.textColor = [UIColor colorWithHexString:@"#7F7F7F"];
        self.textNumberLabel.text=@"0/50";
    }else{
        self.textNumberLabel.text=[NSString stringWithFormat:@"%ld/50",(long)textView.text.length];
    }
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:@"此时想写些什么呢..."]){
        textView.text=@"";
        self.textNumberLabel.text=@"0/50";
        textView.textColor=[UIColor colorWithHexString:@"#2e2e2e"];
    }
}

#pragma mark textField的字数限制
//在这个地方计算输入的字数
- (void)textViewDidChange:(UITextView *)textView
{
    NSInteger wordCount = textView.text.length;
    self.textNumberLabel.text = [NSString stringWithFormat:@"%ld/50",  (long)wordCount];
    [self wordLimit:textView];
}
#pragma mark 超过50字不能输入
-(BOOL)wordLimit:(UITextView *)text{
    if (text.text.length < 50) {
        DLog(@"%ld",(long)text.text.length);
        self.inputDesTextView.editable = YES;
    }
    else{
        self.inputDesTextView.editable = YES;
        self.inputDesTextView.text=[self.inputDesTextView.text substringWithRange:NSMakeRange(0, 50)];
        self.textNumberLabel.text = @"50/50";
    }
    return NO;
}


//拍摄完成后要执行的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    __weak typeof(self) weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    //    UIKIT_EXTERN NSString *const UIImagePickerControllerMediaType; //指定用户选择的媒体类型
    //    UIKIT_EXTERN NSString *const UIImagePickerControllerOriginalImage; // 原始图片
    //    UIKIT_EXTERN NSString *const UIImagePickerControllerEditedImage; // 修改后的图片
    //    UIKIT_EXTERN NSString *const UIImagePickerControllerCropRect; // 裁剪尺寸
    //    UIKIT_EXTERN NSString *const UIImagePickerControllerMediaURL; // 媒体的URL
    //    UIKIT_EXTERN NSString *const UIImagePickerControllerReferenceURL NS_AVAILABLE_IOS(4_1); // 原件的URL
    //    UIKIT_EXTERN NSString *const UIImagePickerControllerMediaMetadata //当数据来源是相机的时候获取到的静态图像元数据，可以使用phtoho框架进行处理
    //
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    NSData *data;
    
    if ([mediaType isEqualToString:@"public.image"]){
        
        //切忌不可直接使用originImage，因为这是没有经过格式化的图片数据，可能会导致选择的图片颠倒或是失真等现象的发生，从UIImagePickerControllerOriginalImage中的Origin可以看出，很原始
        UIImage *originImage = [info objectForKey:UIImagePickerControllerEditedImage];
        
        if (originImage==nil) {
            originImage =[info objectForKey:UIImagePickerControllerOriginalImage];
        }
        
        //图片压缩，因为原图都是很大的，不必要传原图
        UIImage *scaleImage = [self scaleImage:originImage toScale:0.6];
        
        //以下这两步都是比较耗时的操作，最好开一个HUD提示用户，这样体验会好些，不至于阻塞界面
        if (UIImagePNGRepresentation(scaleImage) == nil) {
            //将图片转换为JPG格式的二进制数据
            data = UIImageJPEGRepresentation(scaleImage, 1);
        } else {
            //将图片转换为PNG格式的二进制数据
            data = UIImagePNGRepresentation(scaleImage);
        }
        
        //将二进制数据生成UIImage
        UIImage *image = [UIImage imageWithData:data];
        
        UIView *itemAddImageView = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.preframe)+15, self.preframe.origin.y, self.imageWidth, self.imageWidth+15)];
        
        UIImageView *imageView =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.imageWidth, self.imageWidth)];
        imageView.image = image;
        [itemAddImageView addSubview:imageView];
        
        UIView *deleteView =[[UIView alloc]initWithFrame:CGRectMake(self.imageWidth-40, -10, 50, 50)];
        UIImageView *deleteImageView =[[UIImageView alloc]initWithFrame:CGRectMake(30, 0, 20, 20)];
        deleteImageView.image = [UIImage imageNamed:@"删除"];
        [deleteView addSubview:deleteImageView];
        [itemAddImageView addSubview:deleteView];
        self.selectImageNumber++;
        itemAddImageView.tag =100+self.selectImageNumber;
        
        [self.mainSelectImageContentView addSubview:itemAddImageView];
        
        
        [[SINAUiviewClickLiserner alloc]viewClickFunction:deleteView andWithBlick:^(UIView *view) {
            NSInteger deleteFlag =itemAddImageView.tag-100;
            DLog(@"删除 %ld",(long)deleteFlag);
            //删除
            for (UIView *subviews in [weakSelf.mainSelectImageContentView subviews]) {
                if (subviews.tag==itemAddImageView.tag) {
                    [subviews removeFromSuperview];
                }
            }
            //重新排列所有的子view
            for (NSInteger i=0; i<[[weakSelf.mainSelectImageContentView subviews] count]; i++) {
                UIView *subviews =[weakSelf.mainSelectImageContentView subviews][i];
                [UIView animateWithDuration:0.35 animations:^{
                    if (i>0&&i<=3) {
                        subviews.frame=CGRectMake((weakSelf.imageWidth+15)*(i-1), 15, weakSelf.imageWidth, weakSelf.imageWidth);
                    }else{
                        subviews.frame=CGRectMake((weakSelf.imageWidth+15)*(i-4), weakSelf.imageWidth+30, weakSelf.imageWidth, self.imageWidth);
                    }
                }];
            }
            if ([[weakSelf.mainSelectImageContentView subviews]count]>1) {
                
                
                UIView *lastSubviews=[weakSelf.mainSelectImageContentView subviews][[[weakSelf.mainSelectImageContentView subviews] count]-1 ];
                weakSelf.preframe=lastSubviews.frame;
                [UIView animateWithDuration:0.35 animations:^{
                    weakSelf.addImageView.frame=CGRectMake(lastSubviews.frame.origin.x+15+weakSelf.imageWidth, lastSubviews.frame.origin.y, weakSelf.imageWidth, weakSelf.imageWidth);
                }];
                
            }else{
                weakSelf.preframe=CGRectMake(-15, 15,0,0);
                [UIView animateWithDuration:0.35 animations:^{
                    weakSelf.addImageView.frame=CGRectMake(0, 15,weakSelf.imageWidth,weakSelf.imageWidth);
                }];
            }
            
            if ([[weakSelf.mainSelectImageContentView subviews]count]<=3) {
                weakSelf.mainSelectImageContentView.frame=CGRectMake(15, CGRectGetMaxY(weakSelf.textNumberLabel.frame)+15, mainW-30, weakSelf.imageWidth+15);
                weakSelf.mainContentView.frame=CGRectMake(0, 0, mainW, CGRectGetMaxY(weakSelf.mainSelectImageContentView.frame)+15);
            } else {
                weakSelf.mainSelectImageContentView.frame=CGRectMake(15, CGRectGetMaxY(weakSelf.textNumberLabel.frame)+30, mainW-30, weakSelf.mainSelectImageContentView.frame.size.height+ weakSelf.imageWidth+15);
                weakSelf.mainContentView.frame=CGRectMake(0, 0, mainW, CGRectGetMaxY(weakSelf.mainSelectImageContentView.frame)+15);
            }
            weakSelf.addImageView.hidden=NO;
            
        }];
        
        
        self.preframe=CGRectMake(CGRectGetMaxX(self.preframe)+15, self.preframe.origin.y, self.imageWidth, self.imageWidth);
        self.addImageView.frame=CGRectMake(self.preframe.origin.x+15+self.imageWidth, self.preframe.origin.y, self.imageWidth, self.imageWidth);
        
        
        if (CGRectGetMaxX(self.addImageView.frame)+15>=mainW&&self.mainSelectImageContentView.subviews.count<7) {
            self.preframe=CGRectMake(-15, self.imageWidth+30, 0,0);
            self.addImageView.frame=CGRectMake(0, self.imageWidth+30, self.imageWidth, self.imageWidth);
            self.mainSelectImageContentView.frame=CGRectMake(self.mainSelectImageContentView.frame.origin.x, self.mainSelectImageContentView.frame.origin.y, self.mainSelectImageContentView.frame.size.width, self.mainSelectImageContentView.frame.size.height+self.imageWidth+15);
            self.mainContentView.frame=CGRectMake(self.mainContentView.frame.origin.x, self.mainContentView.frame.origin.y, self.mainContentView.frame.size.width, self.mainContentView.frame.size.height+self.imageWidth+15);
        }
        
        if (self.mainSelectImageContentView.subviews.count>=7) {
            self.addImageView.hidden=YES;
            self.preframe=CGRectMake(-15, 15,0,0);
        }else{
            self.addImageView.hidden=NO;
        }
        
    }
    
}


#pragma mark- 缩放图片
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

//上传图片
-(void)uploadDataFunction{
    
    
    [self.view endEditing:YES];
    if (self.isUpLoading) {
        return;
    }
    self.isUpLoading = YES;
    
    NSString *targetString =self.inputDesTextView.text;
    
    if (targetString.length==0||[targetString isEqualToString:@"此时想写些什么呢..."]) {
        NSString *message =@"请输入随笔内容";
        WISAlertView *alertView =  [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    
     [self.otherImageArray removeAllObjects];
    //上传图片
    NSMutableArray *imageArray = [[NSMutableArray alloc]init];
    
    for (NSInteger i=0; i<self.mainSelectImageContentView.subviews.count; i++) {
        if (i!=0) {
            UIView *itemView = self.mainSelectImageContentView.subviews[i];
            UIImageView *flagImageView = itemView.subviews[0];
            UIImage *imge =flagImageView.image;
            [imageArray addObject:imge];
        }
    }
    if (imageArray.count>0) {

        [self startLoadingWithOrginY:-40];
        
        WeakSelf;
        //上传图片
        [CXAFNHttpRequestUtils httpPostFileRequestWithParamters:nil withImageArray:imageArray success:^(id responseData) {
            NSString *code = responseData[@"code"];
            [weakSelf stopLoading];
            if ([code isEqualToString:@"1000"]) {
                NSArray *imageArray = responseData[@"content"];
                if (imageArray!=nil&&imageArray.count>0) {
                    for (NSInteger i=0; i<imageArray.count; i++) {
                        NSString *titleImageUrl = imageArray[i];
                        [self.otherImageArray addObject:titleImageUrl];
                    }
                    [YPXToastView showToastViewWithText:@"上传成功" andDuration:2 andCorner:5 andParentView:weakSelf.view];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.52*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakSelf saveDataFunction];
                    });
                    
                }else{
                    WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"上传图片数据异常" sureBtn:@"确定"
                                                                         cancleBtn:nil];
                    [alertView showXLAlertView];
                }
                
                
                
                
            }else if ([code isEqualToString:@"1003"]) {
                WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"验证失败" sureBtn:@"确定" cancleBtn:nil];
                [alertView showXLAlertView];
                self.isUpLoading = NO;
            }else{
                NSString *message =responseData[@"message"];
                WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:nil];
                [alertView showXLAlertView];
                 self.isUpLoading = NO;
            }
            
        } failure:^(NSError *error, NSInteger code) {
            
            [weakSelf stopLoading];
             self.isUpLoading = NO;
            [YPXToastView showToastViewWithText:@"网络异常" andDuration:3 andParentView:self.view];
        }];
        
        return;
    }else{
        [self saveDataFunction];
    }
    
}
//提交保存数据
-(void)saveDataFunction{
  
    [self startLoading];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setObject:self.inputDesTextView.text forKey:@"content"];
    [dict setObject:self.model.activityUid forKey:@"organizeuuid"];
    NSString *imgs=@"";
    if (self.otherImageArray.count>0) {
        for (NSInteger i=0; i<self.otherImageArray.count; i++) {
            if (imgs.length==0) {
                imgs = self.otherImageArray[i];
            } else {
                imgs=[NSString stringWithFormat:@"%@,%@",imgs,self.otherImageArray[i]];
            }
        }
    }
    [dict setObject:[NSString stringWithFormat:@"%@", imgs] forKey:@"imgpath"];

    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userActivityAddImpressUrl] withParamters:dict2 success:^(id responseData) {
        NSString *code = responseData[@"code"];
       
        [weakSelf stopLoading];
         self.isUpLoading = NO;
        if ([code isEqualToString:@"1000"]) {
            //添加成功
//            weakSelf.loadingView.text=@"添加成功";
            [YPXToastView showToastViewWithText:@"添加成功" andDuration:2 andCorner:5 andParentView:weakSelf.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
                //创建通知
                NSNotification *notification =[NSNotification notificationWithName:@"addImpressNotification" object:nil userInfo:dict];
                // 通过 通知中心 发送 通知
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                
                //创建通知
                NSNotification *notification2 =[NSNotification notificationWithName:@"stuActivityAddFindOther" object:nil userInfo:dict];
                // 通过 通知中心 发送 通知
                [[NSNotificationCenter defaultCenter] postNotification:notification2];
                
                
                
                [weakSelf.navigationController popViewControllerAnimated:YES];
                
            });
        }else{
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =  [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }
        
    } failure:^(NSError *error, NSInteger errCode) {
        [weakSelf stopLoading];
        self.isUpLoading = NO;
        [YPXToastView showToastViewWithText:@"网络异常" andDuration:3 andParentView:self.view];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}


@end
